const reg = /[xy]/g
const uuid = function () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(reg, (c) => {
    const r = Math.random() * 16 | 0
    // eslint-disable-next-line no-mixed-operators
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16).slice(0, 8)
  })
}

export default class LayerController {
  /**
   * 定义图层类，存储图层的文本、图像地址、位置信息
   * @param {'text' | 'image'} type 定义图层为文本图层/图像图层
   * @param {string} content 图层内容-文本图层的文字/图像的地址
   * @param {number} offsetWidth 父组件宽度
   * @param {number} offsetHeight 父组件高度
   * TODO：后续优化将宽度和高度定义为百分比
   */
  constructor (type, content, offsetWidth, offsetHeight) {
    this.x = offsetWidth / 2
    this.y = offsetHeight / 2
    this.width = 100
    this.height = 100
    this.rotation = 0
    this.id = uuid()
    this.type = type
    this.content = content
  }

  setRect (obj) {
    this.x = obj.x
    this.y = obj.y
    this.width = obj.w
    this.height = obj.h
    this.rotation = obj.angle
    return {
      x: this.x,
      y: this.y,
      w: this.width,
      h: this.height,
      angle: this.rotation
    }
  }

  /**
   * 生成json对象
   */
  toJSON () {
    return {
      x: this.x,
      y: this.y,
      width: this.width,
      height: this.height,
      rotation: this.rotation,
      id: this.id,
      type: this.type,
      content: this.content
    }
  }

  /**
   * @param {Object} obj 从json对象初始化控制器
   */
  fromJSON (obj) {
    for (let key in obj) {
      const that = this
      that[key] = obj[key]
    }
  }
}
